﻿using ADODB;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using LKU8.shoukuan;
using MailKit.Search;
using SqlSuarEntity;
using SqlSugar;
using SqlSugar.DistributedSystem.Snowflake;
using SqlSugar.Extensions;
using System.Data;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Security.Cryptography;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.XXXEntities;
using ZDEntity;
using static XXX.Models.MO.API_Morder;

namespace Yonyou.U8.BO
{

    public class RdRecord10VM : ST_Rdrecord10
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";

        public RdRecord10VM(Rd10Head head, List<Rd10Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

       

        public  RetModel2 AddVerify()
        {
            try
            {
                string idcheck = "";
                if (Exists(ref idcheck))
                {
                    return DBService.ReErrObject($"当前单据号{this.head.ccode}已存在");
                }
                foreach (Rd10Body body in bodies)
                {
                    body.editprop = "A";
                }

                string cRe = GetAddInfo();
                if (cRe != "ok")
                {
                    return DBService.ReErrObject("获取基础信息失败:" + cRe);
                }



                if (!Rdrecord10DALCO.AddVerifyRdrecord10(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        DateTime dDate = DbHelper.GetDbDate(head.ddate);
                        int iid = DbHelper.GetDbInt(id);
                        db.Updateable<rdrecord10>()
                  .SetColumns(u => new rdrecord10()
                  {
                      dVeriDate = dDate,
                      cHandler = head.cmaker
                  })
                  .Where(u => u.ID == iid)
                  .ExecuteCommand();
                        ////不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                        //if (!bWMS)
                        //{

                        //    if (ccode != head.ccode && head.ccode != WMSPara.rd01Code)
                        //    {
                        //        //单据编码选项判断
                        //        string sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0411'");
                        //        int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                        //        if (iRepeat == 1)
                        //        {
                        //            string cerr2 = "";
                        //            Rdrecord10DALCO.VerifyRdrecord10(id, xmlConfig, "unverify,delete", out cerr2);
                        //            return DBService.ReOKObject("单据已生成，重复");
                        //        }
                        //    }
                        //}
                        //else
                        //{
                        //    //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                        //    string cParentid = head.cdefine10;
                        //    if (!string.IsNullOrEmpty(cParentid))
                        //    {
                        //        //检查cParentid 是否存在
                        //        string sqlcx = string.Format(@"select count(*) sl from rdrecord10 a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                        //        int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                        //        if (icntUniq > 0)
                        //        {
                        //            Rdrecord10DALCO.VerifyRdrecord10(id, xmlConfig, "unverify,delete", out _);
                        //            return DBService.ReOKObject("之前单据已生成，重复");
                        //        }
                        //    }

                        //}
                    }
                }
                //生成的id赋值
                head.id = id;
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }



        public RetModel2 Add()
        {
            try
            {
                string idcheck = "";
                //不是wms生成的，检查单据号是否存在
                if (!bWMS && Exists(ref idcheck))
                {
                    return DBService.ReErrObject("当前产成品入库单号已存在");
                }
                foreach (Rd10Body body in bodies)
                {
                    body.editprop = "A";
                }

                if (!Rdrecord10DALCO.AddRdrecord10(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                //else
                //{
                //    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                //    {
                //        ConnectionString = conStr,
                //        DbType = SqlSugar.DbType.SqlServer,
                //        IsAutoCloseConnection = true
                //    }))
                //    {

                //        //不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                //        if (!bWMS)
                //        {

                //            if (ccode != head.ccode && head.ccode != WMSPara.rd01Code)
                //            {
                //                //单据编码选项判断
                //                string sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0411'");
                //                int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                //                if (iRepeat == 1)
                //                {
                //                    string cerr2 = "";
                //                    Rdrecord10DALCO.VerifyRdrecord10(id, xmlConfig, "delete", out cerr2);
                //                    return DBService.ReOKObject("单据已生成，重复");
                //                }
                //            }
                //        }
                //        else
                //        {
                //            //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                //            string cParentid = head.cdefine10;
                //            if (!string.IsNullOrEmpty(cParentid))
                //            {
                //                //检查cParentid 是否存在
                //                string sqlcx = string.Format(@"select count(*) sl from rdrecord10 a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                //                int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                //                if (icntUniq > 0)
                //                {
                //                    Rdrecord10DALCO.VerifyRdrecord10(id, xmlConfig, "delete", out _);
                //                    return DBService.ReOKObject("之前单据已生成，重复");
                //                }
                //            }

                //        }
                //    }
                //}
                //生成的id赋值
                head.id = id;
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }



        /// <summary>
        /// 采购订单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前单据号已删除");
                }
                else
                {
                    head.id = ID;
                }

                if (!Rdrecord10DALCO.VerifyRdrecord10(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }

                return DBService.ReOKObject(head.ccode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        /// <summary>
        /// 完善入库信息,处理部门，辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetAddInfo()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        string cInvCode = bodies[i].cinvcode;
                        WMS_GetSource source = new WMS_GetSource();
                        if (head.csource == "生产订单")
                        { 
                            int iSourceid = DbHelper.GetDbInt(bodies[i].impoids);
                            source = db.Queryable<mom_orderdetail>()
                            .InnerJoin<mom_order>((a, b) => a.MoId == b.MoId && a.MoDId == iSourceid)
                            .Select((a, b) => new WMS_GetSource
                            {
                                ID = b.MoId,
                                cCode = b.MoCode,
                                cDepCode =a.MDeptCode,   
                                cInvCode = a.InvCode,
                                cUnitID = a.AuxUnitCode, 
                                cbMemo = a.Remark,
                                iChangeRate = a.ChangeRate,
                                cMoCode = b.MoCode,
                                iMoSeq = a.SoSeq 
                            }).First();
                            if (source == null)
                            {
                                return string.Format("第{0}行生产订单查询不到", (i + 1).ToString());
                            }

                            if (i == 0 && source != null)
                            {
                                head.cdepcode = source.cDepCode;
                                //head.cpersoncode = source.cPersonCode;
                                //head.crdcode = source.cRdCode; 
                                head.cmpocode = source.cCode;
                                head.iproorderid = DbHelper.GetDbString(source.ID); 
                            }
                            
                            if (bodies[i].cinvcode != "H000000001" && bodies[i].cinvcode != "H000000002")
                            {
                                //排除两个回料
                                if (source.cInvCode != bodies[i].cinvcode )
                                {
                                    return string.Format("第{0}行订单物料{1}不一致", (i + 1).ToString(), cInvCode);
                                }

                                //没有检查自由项,是否和来源订单一样
                                bodies[i].cinvcode = source.cInvCode;
                                bodies[i].cmocode = source.cMoCode;
                                bodies[i].imoseq = DbHelper.GetDbString(source.iMoSeq);
                                bodies[i].cassunit = source.cUnitID;
                            }
                            else
                            {
                                bodies[i].brelated = "1";
                                bodies[i].cmocode = source.cMoCode;
                                bodies[i].imoseq = DbHelper.GetDbString(source.iMoSeq);
                                bodies[i].iorderdetailid = DbHelper.GetDbString(iSourceid);

                                var allocateid = db.Queryable<mom_moallocate>()
                                            .Where(a => a.MoDId == iSourceid && a.InvCode == bodies[i].cinvcode)
                                            .Select(a => a.AllocateId).First() ;  
                                //查询id
                                bodies[i].impoids = DbHelper.GetDbString(allocateid);
                            }
                        }
                        //else
                        //{

                        //    return "无来源单据，无需处理";

                        //}
                        
                        InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, bodies[i].dmadedate, bodies[i].dvdate);
                        if (invProperty == null)
                        {
                            return string.Format("第{0}行订单物料{1}不存在", (i + 1).ToString(), cInvCode);
                        }
                        //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                        if (invProperty.iGroupType != "0")
                        {
                            //辅助计量单位来源于来源单据，如果没有取库存单位
                            if (string.IsNullOrEmpty(bodies[i].cassunit))
                            {
                                bodies[i].cassunit = invProperty.cSTComUnitCode;
                            }

                            if (string.IsNullOrWhiteSpace(DbHelper.GetDbString(source.iChangeRate)))
                            {
                                bodies[i].iinvexchrate = invProperty.iChangRate;
                            }
                            else
                            {
                                bodies[i].iinvexchrate = DbHelper.GetDbString(source.iChangeRate);
                            }
                            if (!string.IsNullOrWhiteSpace(bodies[i].iinvexchrate) && DbHelper.GetDbdecimal(bodies[i].iinvexchrate) != 0.00m)
                            {
                                bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                            }
                             
                        }

                        //是否批次管理
                        if (!invProperty.bInvBatch)
                        {
                            bodies[i].cbatch = "";
                        }
                        else if (string.IsNullOrEmpty(bodies[i].cbatch))
                        {
                            return string.Format("第{0}行订单物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                        }
                        //自由项，未处理

                        //有效期管理,根据生产日期或者失效日期推算 
                        if (invProperty.bInvQuality)
                        {
                            if (string.IsNullOrEmpty(bodies[i].dmadedate) && string.IsNullOrEmpty(bodies[i].dvdate))
                            {
                                return string.Format("第{0}行订单物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                            else
                            {
                                bodies[i].dvdate = DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].imassdate = DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cmassunit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dexpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iexpiratdatecalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }


                        }

                        FitemVM fitemVM = new FitemVM();

                        if (fitemVM.GetName(bodies[i].citem_class, bodies[i].citemcode, out string citem_cname, out string citemname) == "ok")
                        {
                            bodies[i].citemcname = citem_cname;
                            bodies[i].cname = citemname;
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }


            return "ok";
        }


        /// <summary>
        /// 万吉的入单 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RetModel2 Add_WanJi(WanJi_Rd10_View_Lst obj)
        {
            
            var firstEntity = obj.vouList[0];
            if (ExistsByWanJiRd10(obj.vouList[0]))
            {
                return DBService.ReErrObject($"订单号{obj.vouList[0].cMoCode},日期{obj.vouList[0].dDate},班次{obj.vouList[0].cBanCi}的入库单已存在,不能重复导入;");
            }

            try
            {
                ST_Rdrecord10.Rd10Head head = new ST_Rdrecord10.Rd10Head
                {
                    bWireless = "1",
                    cvouchtype = "10",
                    cbustype = "成品入库",
                    csource = "生产订单", 
                    ccode= "0000000005", //设置默认值
                    brdflag = "1",
                    crdcode = "102", //默认值
                    //cdefine1 = obj.cCode,
                    ddate = DbHelper.GetDbDate(firstEntity.dDate).ToString("yyyy-MM-dd"),
                    //仓库和部门没有写，根据生产订单获取
                    //cpersoncode = obj.cPersonCode,
                    //cdepcode = obj.cDepCode,
                    cmaker = obj.cMaker, 
                    dveridate = DbHelper.GetDbDate(firstEntity.dDate).ToString("yyyy-MM-dd"),
                    //chandler = obj.cHandler,
                    //cmemo = obj.cMemo,

                    iswfcontrolled = "0",
                    vt_id = "63",
                    bomfirst = "0",
                    iPrintCount = "0",
                    
                };


                List<LH.Model.ST.ST_Rdrecord10.Rd10Body> bodies = new List<LH.Model.ST.ST_Rdrecord10.Rd10Body>();
                if (obj.vouList != null && obj.vouList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.vouList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }
                            //读取生产订单的信息
                            int iSourceid = DbHelper.GetDbInt(item.autoid);
                            WMS_GetSource source = db.Queryable<mom_orderdetail>()
                            .InnerJoin<mom_order>((a, b) => a.MoId == b.MoId && b.MoCode==item.cMoCode && a.InvCode==item.cInvCode)
                            .Select((a, b) => new WMS_GetSource
                            {
                                ID = b.MoId,
                                cCode = b.MoCode,
                                cDepCode = a.MDeptCode,
                                cWhCode = a.WhCode,
                                cInvCode = a.InvCode,
                                cUnitID = a.AuxUnitCode,
                                cbMemo = a.Remark,
                                iChangeRate = a.ChangeRate,
                                cMoCode = b.MoCode,
                                iMoSeq = a.SoSeq,
                                iMoDid = a.MoDId,
                                iorderid =a.OrderDId,
                                iorderseq = a.OrderSeq,
                                iordertype = a.OrderType,
                                cordercode =a.OrderCode,
                                SoDId = a.SoDId,
                                SoType = a.SoType,
                                cSOCode = a.SoCode,
                                isorowno = a.SoSeq 
                            }).First();
//                            select iorderdid, iordertype, iordercode, iorderseq, isodid, isotype, csocode, isoseq from rdrecords10

//select OrderType,OrderDId,OrderCode,OrderSeq from mom_orderdetail
                            if (source == null)
                            {
                                return  DBService.ReErrObject($"生产订单号{item.cMoCode}下没有产品{item.cInvCode}");
                            }

                            if (i == 0 && source != null)
                            {
                                head.cdepcode = source.cDepCode;
                                head.cwhcode = source.cWhCode;
                                //head.cpersoncode = source.cPersonCode;
                                //head.crdcode = source.cRdCode; 
                                head.cmpocode = source.cCode;
                                head.iproorderid = DbHelper.GetDbString(source.ID);
                                
                                //head.cdefine10 = 
                            }
                            

                            i++;
                            ST_Rdrecord10.Rd10Body body = new ST_Rdrecord10.Rd10Body
                            {
                                editprop = "A",
                                cinvcode = item.cInvCode, 
                                irowno = i.ToString(),
                                iquantity = DbHelper.GetDbString(item.iQuantity),
                                
                                //cbatch = item.cBatch,
                                //cposition = item.cPosCode,
                                //inum = DbHelper.GetDbString(item.iNum),
                                //cbmemo = item.cBMemo,
                                //citemcode = item.cItemCode,
                                //citemcname = item.cItem_Name,
                                //citem_class = item.cItem_Class,
                                //万吉，参照生产订单入库
                                cmocode = item.cMoCode, 
                                impoids = DbHelper.GetDbString(source.iMoDid),
                                imoseq = DbHelper.GetDbString(source.iMoSeq),
                                iorderdid = DbHelper.GetDbString(source.iorderid), 
                                iordertype = DbHelper.GetDbString(source.iordertype),
                                iorderseq = DbHelper.GetDbString(source.iorderseq),
                                iordercode = DbHelper.GetDbString(source.cordercode),
                                isodid = DbHelper.GetDbString(source.SoDId),
                                isotype = DbHelper.GetDbString(source.SoType),
                                csocode = DbHelper.GetDbString(source.cSOCode),
                                isoseq = DbHelper.GetDbString(source.isorowno),
                                cbdefine1 = item.cXianBie,
                                cbdefine2 = item.cBanCi,
                                cdefine33 = item.cPlanCode

                            }; 

                            bodies.Add(body);
                        }
                    }
                }
                this.head = head;
                this.bodies = bodies;

                if (!Rdrecord10DALCO.AddRdrecord10(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    return DBService.ReErrObject("新增失败：" + err);
                }
                else
                {
                    //写入工时

                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {
                        //更新工时
                        string sql = $@"insert into zdy_wanji_gongshi(autoid) select autoid from rdrecord10 a,rdrecords10 b where a.id  = b.id and a.id={id}
and   not exists(select 1 from zdy_wanji_gongshi c where b.autoid = c.autoid)";
                        db.Ado.ExecuteCommand(sql);
                        int iok = 0;
                        foreach (var item in obj.vouList)
                        {
                            sql = @$"update zdy_wanji_gongshi set dworkerqty=@dworkerqty,dworkhr=@dworkhr,dmachinehr=@dmachinehr,dindirectqty=@dindirectqty, dxianqty=@dxianqty 
where autoid = (select autoid from rdrecords10 where id=@id and cmocode=@cmoCode and cinvcode = @cinvcode)";
                           int ire =  db.Ado.ExecuteCommand(sql, new
                            {
                                dworkerqty = item.dworkerqty,
                                dworkhr = item.dworkhr,
                                dmachinehr = item.dmachinehr,
                                dindirectqty = item.dindirectqty,
                                dxianqty = item.dxianqty,
                                id = id,
                                cinvcode = item.cInvCode,
                                cmoCode = item.cMoCode
                            });
                            if (ire>0)
                            {
                                iok++;
                            }
                        }
                        if (iok != obj.vouList.Count)
                        {
                            return DBService.ReOKObject("入库单生成成功，工时写入失败");
                        }
                        else
                        {
                            return DBService.ReOKObject("入库单生成成功，工时写入成功");
                        }
                    }
                   
                }
                    
                    //生成的id赋值
                    head.id = id;
                return DBService.ReOKObject(ccode);


               

            }
            catch (Exception ex)
            {
              
                return DBService.ReErrObject(ex.Message);
            }

        }


        /// <summary>
        /// 万吉的更新工时
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RetModel2 Update_WanJi_WorkHour(WanJi_Rd10_View_Lst obj)
        {

            var firstEntity = obj.vouList[0];
            int id = GetRd10ID(firstEntity);
            if(id==0)
            {
                return DBService.ReErrObject("未找到对应的入库单");
            }
            else
            {
                try
                {
                     
                        //写入工时

                        using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = conStr,
                            DbType = SqlSugar.DbType.SqlServer,
                            IsAutoCloseConnection = true
                        }))
                        {
                            //更新工时
                            string sql = $@"insert into zdy_wanji_gongshi(autoid) select autoid from rdrecord10 a,rdrecords10 b where a.id  = b.id and a.id={id}
and  and not exists(select 1 from zdy_wanji_gongshi c where b.autoid = c.autoid)";
                            db.Ado.ExecuteCommand(sql);
                            int iok = 0;
                            foreach (var item in obj.vouList)
                            {
                                sql = @$"update zdy_wanji_gongshi set dworkerqty=@dworkerqty,dworkhr=@dworkhr,dmachinehr=@dmachinehr,dindirectqty=@dindirectqty, dxianqty=@dxianqty 
where autoid = (select autoid from rdrecords10 where id=@id and cmocode=@cmoCode and cinvcode = @cinvcode)";
                                int ire = db.Ado.ExecuteCommand(sql, new
                                {
                                    dworkerqty = item.dworkerqty,
                                    dworkhr = item.dworkhr,
                                    dmachinehr = item.dmachinehr,
                                    dindirectqty = item.dindirectqty,
                                    dxianqty = item.dxianqty,
                                    id = id,
                                    cinvcode = item.cInvCode,
                                    cmoCode = item.cMoCode
                                });
                                if (ire > 0)
                                {
                                    iok++;
                                }
                            }
                            if (iok != obj.vouList.Count)
                            {
                                return DBService.ReOKObject("入库单生成成功，工时写入失败");
                            }
                            else
                            {
                                return DBService.ReOKObject("入库单生成成功，工时写入成功");
                            }
                        }
                         
                }
                catch (Exception ex)
                {

                    return DBService.ReErrObject(ex.Message);
                }
            }

                

        }
        /// <summary>
        /// 参照产成品入库单的实体
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord10VM GetAddEntity(API_Rdrecord obj, ref string cErr)
        {
             
            try
            {
                ST_Rdrecord10.Rd10Head head = new ST_Rdrecord10.Rd10Head
                {
                    bWireless = "1",
                    cvouchtype = "10",
                    cbustype = "成品入库",
                    csource= "生产订单",
                    ccode = obj.cCode,
                    cwhcode = obj.cWhCode,
                    brdflag = "1",
                    crdcode = obj.cRdCode,
                    //cdefine1 = obj.cCode,
                    ddate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cpersoncode = obj.cPersonCode,
                    cdepcode = obj.cDepCode,
                    cmaker = obj.cMaker,
                    cvencode = obj.cVenCode,
                    dveridate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    chandler = obj.cHandler,
                    cmemo = obj.cMemo,
                   
                    iswfcontrolled = "0",
                    vt_id = "63", 
                    bomfirst = "0",
                    iPrintCount = "0",
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                };


                List<LH.Model.ST.ST_Rdrecord10.Rd10Body> bodies = new List<LH.Model.ST.ST_Rdrecord10.Rd10Body>();
                if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_Rdrecord10.Rd10Body body = new ST_Rdrecord10.Rd10Body
                            {

                                cinvcode = item.cInvCode,
                                cfree1 = item.cFree1,
                                cfree2 = item.cFree2,
                                cfree3 = item.cFree3,
                                cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iquantity = DbHelper.GetDbString(item.iQuantity),
                                cbatch = item.cBatch,
                                cposition = item.cPosCode,
                                inum = DbHelper.GetDbString(item.iNum),
                                cbmemo = item.cBMemo,
                                citemcode = item.cItemCode,
                                citemcname = item.cItem_Name,
                                citem_class = item.cItem_Class,
                                //万吉，参照生产订单入库
                                impoids = item.cSoureRowId,
                                //33自定义项作为mes行id
                                cdefine33 = item.cRowId,

                                //从22 写到37
                                cdefine22 = item.cDefine22,
                                cdefine23 = item.cDefine23,
                                cdefine24 = item.cDefine24,
                                cdefine25 = item.cDefine25,
                                cdefine26 = item.cDefine26,
                                cdefine27 = item.cDefine27,
                                cdefine28 = item.cDefine28,
                                cdefine29 = item.cDefine29,
                                cdefine30 = item.cDefine30,
                                cdefine31 = item.cDefine31,
                                cdefine32 = item.cDefine32,

                                cdefine34 = item.cDefine34,
                                cdefine35 = item.cDefine35,
                                cdefine36 = item.cDefine36,
                                cdefine37 = item.cDefine37

                            };
                            


                            bodies.Add(body);
                        }
                    }
                }



                RdRecord10VM model = new RdRecord10VM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

        }

        /// <summary>
        /// 传入json转换成PurchaseOrderVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord10VM GetCodeEntity(API_Rdrecord obj, ref string cErr)
        {

            try
            {

                ST_Rdrecord10.Rd10Head head = new ST_Rdrecord10.Rd10Head();
                head.ccode = obj.cCode;
                List<ST_Rdrecord10.Rd10Body> bodies = new List<ST_Rdrecord10.Rd10Body>();

                RdRecord10VM model = new RdRecord10VM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }
        /// <summary>
        /// 读取生产订单的modid
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int GetModid(string cMoCode, int iRowno)
        {


            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                var dlsid = db.Queryable<mom_order>()
                                .InnerJoin<mom_orderdetail>((a, b) => a.MoId == b.MoId && a.MoCode == cMoCode && b.SortSeq == iRowno)
                                .Select((a, b) => b.MoDId).First();


                if (dlsid == null)
                {
                    return 0;
                }
                else
                {
                    return dlsid;
                }

            }

        }

        /// <summary>
        /// 检查产成品入库号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from rdrecord10 where ccode='{0}' ", head.ccode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
    
            } 
        
        }

        /// <summary>
        /// 检查产成品入库号是否存在，根据moCode和banCi
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ExistsByWanJiRd10(WanJi_Rd10_View entity)
        {


            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                string sql = @"SELECT COUNT(*) FROM rdrecord10 a inner join rdrecords10 b on a.id= b.id 
inner join rdrecords10_extradefine ex on b.autoid= ex.autoid   
WHERE a.dDate=@dDate and b.cmocode=@cMoCode and ex.cBDefine2=@cBanCi ";
                int icnt = DbHelper.GetDbInt(db.Ado.GetScalar(sql, new {
                dDate = entity.dDate,
                    cMoCode = entity.cMoCode,
                    cBanCi = entity.cBanCi}));

             


                if (icnt > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        }


             /// <summary>
             /// 检查产成品入库号是否存在，根据moCode和banCi
             /// </summary>
             /// <param name="id"></param>
             /// <returns></returns>
        public int GetRd10ID(WanJi_Rd10_View entity)
        {


            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {

                string sql = @"SELECT a.id FROM rdrecord10 a inner join rdrecords10 b on a.id= b.id 
inner join rdrecords10_extradefine ex on b.autoid= ex.autoid   
WHERE a.dDate=@dDate and b.cmocode=@cMoCode and ex.cBDefine2=@cBanCi ";
                int iid = DbHelper.GetDbInt(db.Ado.GetScalar(sql, new
                {
                    dDate = entity.dDate,
                    cMoCode = entity.cMoCode,
                    cBanCi = entity.cBanCi
                }));


                return iid;

            }
        }
    }
}
